/*

 Copyright (c) 2008-2009 Fabrizio Pistonesi

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

 */

#include "eternity3d.h"

//ctor
EternitY3D::EternitY3D(void)
{
	EternitY3D("test");
}
EternitY3D::EternitY3D(stringc project)
{
  loadSettings();
  Driver = Device->getVideoDriver();
  FileSystem = Device->getFileSystem();
  Logger = Device->getLogger();
  if (!FileSystem->existFile("eternity.dat"))
    {
      Logger->log("Could not find \'eternity.dat\'\nCurrent directory is: ", FileSystem->getWorkingDirectory().c_str());
      Device->drop();
      return;
    }
  FileSystem->addZipFileArchive("eternity.dat");

  SceneMgr = new SceneMngr(Device);
/*
  if (project != "")
    {
      IReadFile* rf = FileSystem->createAndOpenFile(project.c_str());
      if (rf)
        {
          // Project is a FILE
          FileSystem->addZipFileArchive(project.c_str());
          Logger->log(
              project.c_str(),
              "\nis a file: NOT supported as project.\nAdded to the filesystem as resource.\n");
          FileSystem->addFolderFileArchive(project.c_str()); //! NOTE this because on linux any param behave as a file
          rf->drop();
        }
      else
        {
          // Project is a FOLDER
          FileSystem->addFolderFileArchive(project.c_str());
          Logger->log(project.c_str(),
              "\nis a directory: added to the filesystem.\n");
          if (rf)
            rf->drop();
        }
      SceneMgr->loadProject(project);
    }
  else
    {*/
      if(Project != "")
        {
          Logger->log("Loading project from \'settings.xml\'.");
          SceneMgr->loadProject(Project);
        }
    //}
}
;

//dtor
EternitY3D::~EternitY3D()
{
  Device->drop();
}
;

bool
EternitY3D::OnEvent(const SEvent& event)
{
  SceneMgr->update(event);

///////// KEY HANDLING /////////
  if (event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.Key
      == KEY_ESCAPE && event.KeyInput.PressedDown == false)
    {
      Device->closeDevice();
    }
  if (event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown == false)
    {
      Nid = SceneMgr->ThisNode->getId();
      int key=(int)(event.KeyInput.Key);
      stringw msg="Unused key: ";
      msg+=key;
      stringw nname, msg2, msg3;

      switch (key)
        {
        case 'I':
          nname = SceneMgr->NodeList[Nid].c_str();
          msg2 = "Current node is: ";
          msg2 += nname;
          msg2 += ". Id: ";
          msg2 += Nid;
          Nid = SceneMgr->ThisNode->getId();
          SceneMgr->getSubtitle()->print(msg2.c_str(),1000);
          break;
        case 'N':
          if(Nid < (int) SceneMgr->NodeList.size()-1)
            {
              SceneMgr->gotoNode(Nid+1,ETT_FADE,500,1.5);
            }
          break;
        case 'B':
          if(Nid > 0)
            {
              SceneMgr->gotoNode(Nid-1,ETT_FADE,500,0.75);
            }
          break;
        case 'R':
          SceneMgr->gotoNode(Nid,ETT_FADE,500,1);
          break;
        case 'C':
          for(unsigned int i = 0; i < SceneMgr->ThisNode->Sounds.size(); i++ )
            {
              bool visible = SceneMgr->ThisNode->getSound(i)->SoundCube->isVisible();
              SceneMgr->ThisNode->getSound(i)->SoundCube->setVisible(!visible);
            }
          for (unsigned int i = 0; i < SceneMgr->ThisNode->Sensors.size(); i++)
          {
            bool visible = SceneMgr->ThisNode->getSensor(i)->isVisible();
            SceneMgr->ThisNode->getSensor(i)->setVisible(!visible);
          }
          break;
        default:
          SceneMgr->getSubtitle()->print(msg.c_str(),500);
          break;
        }

    }
  return false;
}

bool
EternitY3D::loadSettings()
{
  Device = createDevice(EDT_NULL, dimension2d<u32> (0,0), 16,false, false, false);
  IReadFile* rf = Device->getFileSystem()->createAndOpenFile("settings.xml");
  if (!rf)
    {
      Device->getLogger()->log("Unable to find \'settings.xml\'");
      printf("EternitY3D Engine (c)2008-2009 Fabrizio Pistonesi\nVersion: 0.0.9 beta using:\n");
      Device = createDevice(EDT_OPENGL,dimension2d<u32>(640,480),32,false,true);
      return false;
    }
  IXMLReader* reader = Device->getFileSystem()->createXMLReader(rf);
  if (!reader)
    {
      Device->getLogger()->log("Project has not a valid XML file", rf->getFileName().c_str(), ELL_ERROR);
      printf("EternitY3D Engine (c)2008-2009 Fabrizio Pistonesi\nVersion: 0.0.9 beta using:\n");
      Device = createDevice(EDT_OPENGL,dimension2d<u32>(640,480),32,false,true);
      return false;
    }
  while (reader->read())
    {
      bool endreached = false;
      const wchar_t* name = reader->getNodeName();
      switch (reader->getNodeType())
        {
      case EXN_ELEMENT_END:
        if (stringw(L"eternity") == name) endreached = true;
        return true;
        break;
      case EXN_ELEMENT:
        if (stringw(L"attributes") == name)
          {
            IAttributes* attr = Device->getFileSystem()->createEmptyAttributes(Device->getVideoDriver());
            attr->read(reader);
            Project = attr->getAttributeAsString("project");
            position2d<s32> res = attr->getAttributeAsPosition2d("resolution");
            bool fs = attr->getAttributeAsBool("fullscreen");
            SpecialFX = attr->getAttributeAsBool("specialfx");
            Device->drop();
            printf("EternitY3D Engine (c)2008-2009 Fabrizio Pistonesi\nVersion: 0.0.9 beta using:\n");
            Device = createDevice(EDT_OPENGL,dimension2d<u32>(res.X,res.Y),32,fs,true);
          }
        break;
      default:
        break;
        }
      }
    return false;
  }

bool
EternitY3D::run()
{
  //Device->setEventReceiver(this);
  Device->setResizable(true);
  SceneMgr->getSubtitle()->print(L"SUBTITLE initialized correctly.",5000);
  while(Device->run())
    {
      Driver->beginScene(true,true,SColor(0,0,0,0));
      Device->getSceneManager()->drawAll();
      Device->getGUIEnvironment()->drawAll();

      SceneMgr->getSubtitle()->draw();
      SceneMgr->getCursor()->draw();
      SceneMgr->getTransition()->draw();

      Driver->endScene();
    }
  Device->drop();
  return false;
}

